package com.ywjt.pinkelephant.home.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ywjt.pinkelephant.R;
import com.ywjt.pinkelephant.base.BaseActivity;
import com.ywjt.pinkelephant.util.SPUtils;
import com.ywjt.pinkelephant.util.ToastUtil;
import com.ywjt.pinkelephant.widget.PromptBroadsetBottomDialog;
import com.ywjt.pinkelephant.widget.Rotate3dAnimation1;
import com.ywjt.pinkelephant.widget.Rotate3dAnimation2;

import java.lang.ref.WeakReference;

public class ActivityPromptBroad extends BaseActivity implements View.OnClickListener {
    private LinearLayout llContainer;
    private ImageView ivBack,ivSet,ivRestart;
    private TextView tvText;
    private int width=0;
    private int height=0;
    private ImageView ivMirror;
    private RelativeLayout reverse_layout;
    private Boolean isMirror=false;
    private ScrollView scrollView;
    private ImageView ivStartPlay;
    private TextView tvCountDown;
    private MyHandler myHandler=null;

    private final Handler mHandler = new Handler();
    /***********本地广播*************/
    public static LocalBroadcastManager localBroadcastManager;
    private MyBroadcastReceiver myBroadcastReceiver;
    private IntentFilter filter;
    public static String LOCAL_BROADCAST = "com.ywjt.pinkelephant.home.activity.ActivityPromptBroad";

    public void registerMessageReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        myBroadcastReceiver = new MyBroadcastReceiver();
        filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(LOCAL_BROADCAST);
        localBroadcastManager.registerReceiver(myBroadcastReceiver, filter);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (LOCAL_BROADCAST.equals(intent.getAction())) {
                    switch (intent.getIntExtra("action", 1)) {
                        case 1:
                            //背景透明度
                            float t=Float.parseFloat(intent.getStringExtra("value"));
                            llContainer.setAlpha((100-t)/100);
                            SPUtils.setSharedFloatData(ActivityPromptBroad.this,"BoardBgTransParent",t);
                            break;
                        case 2:
                            if (intent.getStringExtra("value").equals("0")){
                                //字体颜色
                                tvText.setTextColor(intent.getIntExtra("color",0));
                                SPUtils.setSharedIntData(ActivityPromptBroad.this,"BoardTextColor",intent.getIntExtra("color",0));
                            }else {
                                //背景颜色
                                llContainer.setBackgroundColor(intent.getIntExtra("color",0));
                                SPUtils.setSharedIntData(ActivityPromptBroad.this,"BoardBgColor",intent.getIntExtra("color",0));
                            }
                            break;
                        case 3:
                            float size=Float.parseFloat(intent.getStringExtra("value"));
                            tvText.setTextSize(size);
                            SPUtils.setSharedFloatData(ActivityPromptBroad.this,"BoardTextSize",size);
                            break;
                        case 4:
                            int margin=Integer.parseInt(intent.getStringExtra("value"));
                            tvText.setPadding(margin*width/100/2-100,0,margin*width/100/2-100,0);
                            SPUtils.setSharedIntData(ActivityPromptBroad.this,"BoardTextMargin",margin);
                            break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void actionStart(Context context ) {
        Intent intent = new Intent(context, ActivityPromptBroad.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivSet:
                //设置
                PromptBroadsetBottomDialog bottomDialog=new PromptBroadsetBottomDialog(ActivityPromptBroad.this);
                bottomDialog.show(getSupportFragmentManager());
                ivStartPlay.setVisibility(View.VISIBLE);
                if (SPUtils.getSharedBooleanData(ActivityPromptBroad.this,"IsChecked")){
                    mHandler.removeCallbacks(ScrollRunnable);
                }
                break;
            case R.id.ivMirror:
                //镜像
                if (!isMirror){
                    Animation animation = new Rotate3dAnimation1(reverse_layout.getWidth() / 2, reverse_layout.getHeight() / 2);
                    animation.setFillAfter(true);
                    reverse_layout.startAnimation(animation);
                }else {
                    Animation animation = new Rotate3dAnimation2(reverse_layout.getWidth() / 2, reverse_layout.getHeight() / 2);
                    animation.setFillAfter(true);
                    reverse_layout.startAnimation(animation);
                }
                isMirror=!isMirror;
                break;
            case R.id.ivStartPlay:
                //开始提词
                tvCountDown.setVisibility(View.VISIBLE);
                ivStartPlay.setVisibility(View.GONE);
                startCountTime();
                break;
            case R.id.tvText:
                mHandler.removeCallbacks(ScrollRunnable);
                ivStartPlay.setVisibility(View.VISIBLE);
                break;
            case R.id.ivRestart:
                scrollView.fullScroll(ScrollView.FOCUS_UP);
                ivStartPlay.setVisibility(View.VISIBLE);
                if (SPUtils.getSharedBooleanData(ActivityPromptBroad.this,"IsChecked")){
                    mHandler.removeCallbacks(ScrollRunnable);
                }
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(false);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_prompt_board;
    }

    /**
      * 滚屏的线程
     */
      private Runnable ScrollRunnable = new Runnable() {
          @SuppressLint("NewApi")
          @Override
          public void run() {
                         int off = tvText.getMeasuredHeight() - scrollView.getHeight();// 判断高度
                         if (off > 0) {
                             scrollView.scrollBy(0, SPUtils.getSharedIntData(ActivityPromptBroad.this,"AiSpeed")/10);
                                 if (scrollView.getScaleY() == off) {
                                     Thread.currentThread().interrupt();
                                 } else {
                                     mHandler.postDelayed(this, 100);
                                 }
                             }
                     }
    };

    @Override
    protected void initView() {
        Display dp = getWindowManager().getDefaultDisplay();
        width = dp.getWidth();
        height = dp.getHeight();
        registerMessageReceiver();
        llContainer=findViewById(R.id.llContainer);
        scrollView=findViewById(R.id.scrollView);
        reverse_layout=findViewById(R.id.reverse_layout);
        ivStartPlay=findViewById(R.id.ivStartPlay);
        ivMirror=findViewById(R.id.ivMirror);
        tvCountDown=findViewById(R.id.tvCountDown);
        ivBack=findViewById(R.id.ivBack);
        tvText=findViewById(R.id.tvText);
        ivRestart=findViewById(R.id.ivRestart);
        ivSet=findViewById(R.id.ivSet);
        ivBack.setOnClickListener(this::onClick);
        ivSet.setOnClickListener(this::onClick);
        ivMirror.setOnClickListener(this::onClick);
        ivStartPlay.setOnClickListener(this::onClick);
        tvText.setOnClickListener(this::onClick);
        ivRestart.setOnClickListener(this::onClick);

        tvText.setText("粉象提词器，一站式视频创作中台。让你轻松写剧本，无需背台词！从创作到拍摄，100万创作者的共同选择！四大核心功能，让你创作的更轻松。智能提词。ai实时识别你的声音，根据你说话的速度来提词，让你可以更自如的面对镜头、表达自己。悬浮提词，安卓版支持提词窗悬浮在");

        if (SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardTextColor")!=0){
            tvText.setTextColor(SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardTextColor"));
        }

        if (SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardBgColor")!=0){
            llContainer.setBackgroundColor(SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardBgColor"));
        }

        if (SPUtils.getSharedFloatData(ActivityPromptBroad.this,"BoardTextSize")!=0){
            tvText.setTextSize(SPUtils.getSharedFloatData(ActivityPromptBroad.this,"BoardTextSize"));
        }

        if (SPUtils.getSharedFloatData(ActivityPromptBroad.this,"BoardBgTransParent")!=0){
            llContainer.setAlpha((100-SPUtils.getSharedFloatData(ActivityPromptBroad.this,"BoardBgTransParent"))/100);
        }

        if (SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardTextMargin")!=0){
            tvText.setPadding(SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardTextMargin")*width/100/2-100,
                    0,
                    SPUtils.getSharedIntData(ActivityPromptBroad.this,"BoardTextMargin")*width/100/2-100,
                    0);
        }

        tvText.setMovementMethod(new ScrollingMovementMethod());
        myHandler=new MyHandler(ActivityPromptBroad.this);
    }

    @Override
    protected void initData() { }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     */
    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }
    /*
     * 创建一个计时的线程，利用handler发送计时的消息
     */
    private void startCountTime() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 3; i > 0; i--) {
                    Message mes = myHandler.obtainMessage();
                    mes.arg1 = i;
                    mes.what = 0x00;//计时中的标志
                    myHandler.sendMessage(mes);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Message mes = myHandler.obtainMessage();
                mes.what = 0x11;//计时完成的标志
                myHandler.sendMessage(mes);

            }
        }.start();
    }

    /**
     * 自定义一个带有MainActivity弱引用的静态Handler
     * 防止内存泄漏
     */
    private  class MyHandler extends Handler {

        WeakReference<ActivityPromptBroad> wr;

        public MyHandler(ActivityPromptBroad activity) {
            //实例化弱引用
            wr = new WeakReference<ActivityPromptBroad>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ActivityPromptBroad activity = wr.get();
            if (activity != null) {//判断该activity是否已经销毁
                switch (msg.what) {
                    case 0x00:
                        tvCountDown.setText(msg.arg1+"");
                        break;
                    case 0x11:
                        tvCountDown.setVisibility(View.GONE);
                        if (SPUtils.getSharedBooleanData(ActivityPromptBroad.this,"IsChecked")){
                            mHandler.post(ScrollRunnable);
                        }
                        break;
                }
            }
        }
    }
}